#extension GL_EXT_gpu_shader4 : enable
#extension GL_ARB_texture_rectangle : enable 

uniform sampler2D BjSampler;
uniform sampler2D deltaBjSampler;
uniform sampler2D shooterDeltaBjSampler;
uniform sampler2DRect becomingVisibleVectorsSampler;
uniform sampler2DArray facePositionsSampler;

uniform vec3 ro;
uniform float shooterFaceArea;
uniform int shooterLevel;
uniform int shooterIndex;
uniform float shooterOffset;
uniform int receiverIndex;
uniform int unshotShooterLevel;

float FormFactor(float shooterDeltaArea);

void main(void)
{
	ivec2 shooterRadiosityTextureSize = textureSize2D(shooterDeltaBjSampler, shooterLevel);
	int shooterRadiosityTextureArea = shooterRadiosityTextureSize.x * shooterRadiosityTextureSize.y;
	ivec2 shooterUnshotLodTextureSize = textureSize2DArray(facePositionsSampler, unshotShooterLevel).xy;
	int shooterUnshotLodTextureArea = shooterUnshotLodTextureSize.x * shooterUnshotLodTextureSize.y;

	vec2 textureIndex = vec2((shooterIndex * shooterUnshotLodTextureArea) + shooterOffset + 1, receiverIndex + 1);

	float shooterTextureArea = min(shooterRadiosityTextureArea, shooterUnshotLodTextureArea);
	float shooterDeltaArea = shooterFaceArea / float(shooterTextureArea);
	//Ratio of the shooter texels per unshot LOD texel
	float shooterUnshotDeltaArea = shooterRadiosityTextureArea / shooterTextureArea;

	vec4 Bj = texture2D(BjSampler, gl_TexCoord[0].st);
	vec4 deltaBj = texture2D(deltaBjSampler, gl_TexCoord[0].st);
	//Average the radiosity values that were supposed to have been shot to this location
	vec3 shootDeltaBj = texture2DRect(becomingVisibleVectorsSampler, textureIndex).rgb / shooterUnshotDeltaArea;

	float Fij = FormFactor(shooterDeltaArea);
	vec4 shotRadiosity = shooterDeltaArea * vec4(ro * shootDeltaBj * Fij, 1);

	gl_FragData[0] = Bj + shotRadiosity;
	gl_FragData[1] = deltaBj + shotRadiosity;
}
